﻿module Runner {
    export class Hero extends Phaser.Sprite implements OffenseDefense {
        jumpTimer: number = 0;
        hitPoints: number = 100;
        maxHitPoints: number = this.hitPoints;
        _lastHitPoints: number = 0;
        atkPower: number = 30;
        dodgeChance: number = 40;
        healthBar: Phaser.Graphics;

        constructor(game: Phaser.Game, x: number, y: number, usesPhysics?: boolean) {
            super(game, x, y, 'Hero', 0);
            this.anchor.setTo(0.5, 0);

            SpriteBuilder.buildAnimation(this);

            if (usesPhysics == true || usesPhysics == null || usesPhysics === undefined) {
                this.physicsEnabled = true;
                SpriteBuilder.setSpritePhysics(this);
                this.game.camera.follow(this);
            }

            

        }

        update() {
            if (this.physicsEnabled) {
                var speed = 150;
                if (Physics.touchingVertical(this, 'bottom')) {
                    this.body.velocity.x = 0;

                    if (this.game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) {
                        this.body.velocity.x -= speed;
                        this.animations.play('walk_left');
                    } else if (this.game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) {
                        this.body.velocity.x += speed;
                        this.animations.play('walk_right');
                    } else {
                        this.animations.frame = 27;
                    }

                    if ((this.game.input.keyboard.isDown(Phaser.Keyboard.UP) || this.game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) && Physics.touchingVertical(this, 'bottom') && this.game.time.now > this.jumpTimer) {
                        this.body.velocity.y -= 450;
                        this.jumpTimer = this.game.time.now + 750;
                    }
                }
            }
        }
    }

    export function getHero(game, keyToFind = 'Hero'): Runner.Hero {
        var hero: Runner.Hero;
        game.world.children.forEach(function (element) {
            if (element.key == keyToFind) {
                hero = element;
            }
        });

        return hero;
    }
}